package secure.access.encrypt;

import com.alibaba.fastjson.JSONObject;
import com.mjk.common.tools.logger.BizLogger;

import java.util.Map;

public class XjbwDataAccess {

    public static String dataAccess(
            String url,
            String companyPriKey,
            String platFormPubKey,
            String content,
            String accessType,
            String enterpriseCode,
            String thirdPlatformCode,
            String reqMsgId,
            String businessCode,
            String productCode,
            String contentType) {

        EncryptEntity encryptEntity;

        // Encrypt the content
        try {
            encryptEntity = XjbwEncryptDecrypt.encryptContent(content, platFormPubKey, companyPriKey);
        } catch (Exception e) {
            BizLogger.info("请求报文加密失败！" + e.getMessage(), e);
            return "{\"secureCode\":\"0001\",\"message\":\"请求报文加密失败！\"}";
        }

        // Validate access type
        if (accessType == null || accessType.isEmpty()) {
            return "{\"secureCode\":\"0001\",\"message\":\"接入方式有误，请检查！\"}";
        }

        // Set properties for encryptEntity
        encryptEntity.setAccessType(accessType);
        encryptEntity.setProductCode(productCode);
        encryptEntity.setEnterpriseCode(enterpriseCode);
        encryptEntity.setThirdPlatformCode(thirdPlatformCode);
        encryptEntity.setReqMsgId(reqMsgId);
        encryptEntity.setBusinessCode(businessCode);

        // Convert encryptEntity to JSON
        String encrypt = JSONObject.toJSONString(encryptEntity);

        String requestContentType;

        // Determine content type
        if ("1".equals(contentType)) {
            requestContentType = "application/json";
        } else if ("2".equals(contentType)) {
            requestContentType = "application/xml";
        } else {
            requestContentType = "text/plain";
        }

        // Send HTTP request
        Map<String, String> resultMsg;
        try {
            resultMsg = HttpsUtil.requestPost(url, encrypt, requestContentType);
            String response = (String) resultMsg.get("result");

            if (!"200".equals(resultMsg.get("code"))) {
                return response;
            }

            // Process response
            if (!isJson(response)) {
                return response;
            }

            JSONObject parseObject = JSONObject.parseObject(response);
            EncryptEntity entity = JSONObject.toJavaObject(parseObject, EncryptEntity.class);

            // Decrypt the response content
            String resultContent;
            try {
                resultContent = XjbwEncryptDecrypt.decryptContent(entity, platFormPubKey, companyPriKey);
            } catch (Exception e) {
                BizLogger.info("返回报文解密失败！" + e.getMessage(), e);
                return "{\"secureCode\":\"0001\",\"message\":\"返回报文解密失败！\"}";
            }

            JSONObject jsonObject = new JSONObject();
            if (isJson(resultContent)) {
                JSONObject resultJson = JSONObject.parseObject(resultContent);
                jsonObject.put("message", resultJson);
            } else {
                jsonObject.put("message", resultContent);
            }

            // Determine secure code based on response content
            String judge = "\"resCode\":\"0\"";
            if (response.contains(judge)) {
                jsonObject.put("secureCode", "0000");
            } else {
                jsonObject.put("secureCode", "0001");
            }

            return jsonObject.toJSONString();

        } catch (Exception e) {
            return JSONObject.toJSONString("发送HTTP请求异常：" + e);
        }
    }

    static boolean isJson(String json) {
        try {
            JSONObject.parse(json);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}
